export default {
	namespaced: true,
	actions:{
		
	},
	mutations:{
		// 向购物车数组中添加商品，数量
		addGoodsToCart(state,goods){
			const goodsItem = state.cart.find((item)=>{
				return item.goods_id == goods.goods_id;
			})
			if(!goodsItem){
				state.cart.push(goods);
			}
			else{
				goodsItem.goods_number += 1;
			}
			this.commit('m_cart/localCartData');
		},
		
		// 更改购物车商品的选中状态
		changeGoodsState(state,goodsId){
			const goodsItem = state.cart.find((item)=>{
				return item.goods_id == goodsId;
			})
			if(goodsItem){
				goodsItem.goods_state = !goodsItem.goods_state;
			}
			this.commit('m_cart/localCartData');
		},
		
		//更改购物车商品的数量
		 changeGoodsNumber(state,goodsData){
			const goodsItem = state.cart.find((item)=>{
				return item.goods_id == goodsData.goods_id;
			 })
			 if(goodsItem){
				 goodsItem.goods_number = goodsData.goods_number;
			 }
			 this.commit('m_cart/localCartData');
		 },
		 
		 // 移除购物车中的商品
		 removeGoods(state,goodsId){
			state.cart = state.cart.filter((item)=>{
				 return item.goods_id !== goodsId;
			 })
			 this.commit('m_cart/localCartData');
		 },
		 
		 // 购物车商品状态跟随全选状态
		 goodsStates(state,checkAllState){
			 state.cart.forEach((item)=>{
				 item.goods_state = checkAllState;
			 })
			 this.commit('m_cart/localCartData');
		 },
		
		// 将购物车商品数据进行本地存储
		localCartData(state){
			uni.setStorageSync('local_cart', JSON.stringify(state.cart))
		}
	},
	state:{
		// 购物车商品数据
		cart: JSON.parse(uni.getStorageSync('local_cart') || '[]')
	},
	getters:{
		// 购物车商品总数
		total(state){
			return state.cart.reduce((count,item)=>{
				return count += item.goods_number;
			},0)
		},
		// 是否全选
		isCheckAll(state){
			let checkAllNum = state.cart.reduce((count,item)=>{
				if(item.goods_state){
					count++;
				}
				return count;
			},0)
			if(checkAllNum == state.cart.length){
				return true;
			}
			else{
				return false;
			}
		},
		// 购物车中已勾选的商品总数
		checkTotal(state){
			return state.cart.reduce((count,item)=>{
				if(item.goods_state){
					count += item.goods_number;
				}
				return count;
			},0)
		},
		// 购物车中已勾选的商品总价格
		checkPrice(state){
			return state.cart.reduce((count,item)=>{
				if(item.goods_state){
					count += item.goods_number * item.goods_price;
				}
				return count;
			},0)
		}
	}
}	